<template>
  <qh-page-view :showNavbar="false" bgColor="#fff">
    <view class="fixed-header" :style="headerStyle">
      <uni-status-bar></uni-status-bar>
      <view class="search-box flex-cn">
        <view class="navbar-left flex-cn" style="flex: 1" @click="backHome">
          <view style="width: 100rpx; text-align: center; color: #fff"
            class="qh-rt-single qh-rt-zuo-zuo navbar-back-icon" :class="{ 'icon-dark': isScrolled }">
          </view>
        </view>

        <view style="font-weight: 600" class="header-title" :class="{ 'text-dark': isScrolled }">
          {{ title }}
        </view>
        <view style="width: 320rpx; flex: 1"></view>
      </view>
    </view>

    <view class="benner_box">
      <view class="obj-money-price-range">
        <scroll-view scroll-x :show-scrollbar="false" enhanced :fast-deceleration="true"
          class="obj-money-scroll-container" :scroll-left="scrollLeft">
          <view class="obj-money-price-list">
            <view v-for="(item, index) in priceRanges" :key="index" :class="[
              'obj-money-price-item',
              selectedIndex === index ? 'active' : '',
            ]" @tap="selectPrice(item, index)">
              {{ item }}
            </view>
          </view>
        </scroll-view>
      </view>

      <view style="
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;
        ">
        <view class="options">
          <view @click="sortBySalesOne" class="option" :class="{ active: activeTab === '1' }">
            <text>销量</text>
            <view class="triangle-icons">
              <view class="triangle-icon triangle-icon-up" :class="{ active: activeTab === '1' && isActiveUp }"></view>
              <view class="triangle-icon triangle-icon-down" :class="{ active: activeTab === '1' && isActiveDown }">
              </view>
            </view>
          </view>
          <view @click="sortByPriceOne" class="option" :class="{ active: activeTab === '2' }">
            <text>价格</text>
            <view class="triangle-icons">
              <view class="triangle-icon triangle-icon-up" :class="{ active: activeTab === '2' && isActiveUp }"></view>
              <view class="triangle-icon triangle-icon-down" :class="{ active: activeTab === '2' && isActiveDown }">
              </view>
            </view>
          </view>

          <view id="brandSelect" @click.stop="showBrandSelect" class="option" :class="{ active: activeTab === '3' }">
            <text >品牌</text>
          </view>
        </view>

        <!-- 品牌选择弹窗 -->
        <view class="fliter-new-popup" v-if="showPopup" @click.stop="hidePopup">
          <view class="fliter-new-popup-content" :class="{ 'fliter-new-slide-out': isClosing }" @click.stop @animationend="onAnimationEnd">
            <view class="fliter-new-title">品牌可多选</view>
            <view class="fliter-new-brand-grid">
              <view v-for="(brand,index) in brands" :key="brand.id" class="fliter-new-brand-item"
                :class="{ 'fliter-new-active': brand_ids.includes(brand.brand_id) }" @click.stop="toggleBrand(index)">
                {{ brand.name }}</view>
            </view>
            <view class="fliter-new-btn-group">
              <view class="fliter-new-btn cancel" @click.stop="hidePopup">取消</view>
              <view class="fliter-new-btn confirm" @click.stop="confirmSelect">确定</view>
            </view>
          </view>
        </view>
      </view>

      <view class="obj-money-list">
        <view class="obj-money-card">
          <view class="obj-money-content" v-for="item in goodsFourList" :key="item.id">
            <image class="obj-money-image" :src="item.goods_image" mode="aspectFit" @click="handleBuy(item)" />
            <view class="obj-money-right" @click="handleBuy(item)">
              <view class="obj-money-title">{{ item.goods_name }}</view>
              <view></view>
              <view>
                <view class="obj-money-bottom">
                  <view class="obj-money-price">
                    <text class="obj-money-symbol">¥</text>
                    <text class="obj-money-value">{{ item.online_price }}</text>
                    <view class="temperature-box" v-if="item.rebate > 0">
                      {{ item.rebate }}<text style="letter-spacing: 2rpx;margin-left: 2rpx;">福气值</text>
                    </view>
                  </view>
                </view>
                <view @click="handleBuy(item)">
                  <buy-button buttonWidth="90%" buttonText="立即加购"></buy-button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="list-money-tail">
          <view class="list-money-boy">
            <ProductGrid :products="productFourList" @add-to-cart="handleBuy" />
          </view>

        <view>
          <moenyScroll :productList="tenList" @on-add="handleBuy" />
          <moenyScroll :productList="tenList2" @on-add="handleBuy" />
        </view>

        <view class="list-money-boy">
          <ProductGrid :products="productList6" @add-to-cart="handleBuy" />
        </view>

        <view>
          <moenyScroll :productList="tenList3" @on-add="handleBuy" />
          <moenyScroll :productList="tenList4" @on-add="handleBuy" />
        </view>
      </view>
    </view>
  </qh-page-view>
</template>

<script>
import ProductGrid from "./components/moeny_product.vue";
import moenyScroll from "./components/moeny_scroll.vue";

export default {
  components: {
    ProductGrid,
    moenyScroll,
  },
  data() {
    return {
      title: "",
      isTop: true,
      activeTab: "",
      isActiveUp: false,
      isActiveDown: false,
      showBubble: true,
      priceRanges: [
        "100元以下",
        "100-200元",
        "200-300元",
        "300-400元",
        "500-800元",
        "800元以上",
      ],
      selectedIndex: 0,
      productList6: [],//六个商品
      goodsFourList: [], //四个商品
      productFourList: [], //四个商品
      tenList: [], //横向十个
      tenList2: [], //横向十个
      tenList3: [], //横向十个
      tenList4: [],
      scrollLeft: 0,
      minPrice: 0,
      maxPrice: 0,
      sort: "",
      showPopup: false,
		isClosing: false,
		popupStyle: {
		  top: '0px'
		},
		brands: [

		],
		selectedBrandNames: '',  // 用于显示选中的品牌名称
    brand_ids: [],
    };
  },
 async onLoad(options) {
    if (options.priceRange) {
      this.title = options.priceRange;
      this.selectedIndex = parseInt(options.selectedIndex);

      if (options.priceRange) {
        this.title = options.priceRange;
        this.selectedIndex = parseInt(options.selectedIndex);

        // 使用封装的方法处理价格
        const { minPrice, maxPrice } = this.handlePriceRange(
          options.priceRange
        );
        this.minPrice = minPrice;
        this.maxPrice = maxPrice;
      }

      // 在下一个渲染周期执行滚动
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".obj-money-scroll-container")
          .boundingClientRect((scrollView) => {
            query
              .select(".obj-money-price-item")
              .boundingClientRect((item) => {
                if (scrollView && item) {
                  // 计算需要滚动的位置
                  // 容器宽度的一半减去item宽度的一半，让item居中
                  const containerCenter = scrollView.width / 2;
                  const itemWidth = item.width;
                  const itemCenter = itemWidth / 2;

                  // 计算目标滚动位置
                  // selectedIndex * (itemWidth + 间距) - (容器中心点 - 项目中心点)
                  this.scrollLeft =
                    this.selectedIndex * (itemWidth + 20) -
                    (containerCenter - itemCenter);

                  setTimeout(() => {
                    uni.pageScrollTo({
                      scrollLeft: this.scrollLeft,
                      duration: 300,
                    });
                  }, 100);
                }
              })
              .exec();
          })
          .exec();
      });
    await  this.getMoneyList();
    await  this.getbrandList()
    }
  },
  computed: {
    headerStyle() {
      return `background-image: ${this.isTop
          ? 'url("https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/17337434366756d34caea20.png")'
          : "none"
        }`;
    },
    styleColor() {
      return `color: ${this.isTop ? "#fff" : "#000 "}`;
    },
  },

  methods: {

   async getbrandList() {

      uni.showLoading({
        title: "加载中...",
        mask: true,
      }); 
     try {
        const res = await this.$request(
          "SmallProgramApi/NewYear/getBrandList",
          {
            store_id: this.$store.mallStoreId,
            merchant_id: 1,
            source_type: 3,
            price_start: this.minPrice,
            price_end: this.maxPrice,
          }
        );
          this.brands = res.data

          console.log(res  ,'232323')
        // if (res.data) {
        //   this.brands = res.data.slice(0, 6);
        // }

      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        // 确保加载状态被清除
          uni.hideLoading();
      }
    },

    //品牌
    showBrandSelect() {
      // 如果已经显示，则隐藏
      if (this.showPopup) {
        this.hidePopup()
        return
      }
      
      // 否则显示
      this.isClosing = false
      const query = uni.createSelectorQuery().in(this)
      query.select('#brandSelect').boundingClientRect(data => {
        if (data) {
          this.popupStyle.top = data.bottom + 'px'
          this.showPopup = true
          this.activeTab = '3'
        }
      }).exec()
    },
    hidePopup() {
      this.isClosing = true
      this.activeTab = ''
    },
    onAnimationEnd() {
      if (this.isClosing) {
        this.showPopup = false
        this.isClosing = false
      }
    },
  toggleBrand(index) {
      console.log('Before toggle:', this.brand_ids);
      const brandId = this.brands[index].brand_id; // Get the ID from the brands array
      const currentIndex = this.brand_ids.indexOf(brandId); // Check if this ID is already in brand_ids
      if (currentIndex === -1) {
          this.brand_ids.push(brandId); // Add the ID if it's not present
      } else {
          this.brand_ids.splice(currentIndex, 1); // Remove the ID if it's present
      }
      console.log('After toggle:', this.brand_ids);
      this.updateSelectedBrandNames();
      console.log(this.brand_ids, '数据');
  },
    updateSelectedBrandNames() {
      const selectedBrands = this.brands.filter((brand, idx) => this.brand_ids.includes(brand.brand_id))
      this.selectedBrandNames = selectedBrands.map(brand => brand.name).join(',')
    },
    confirmSelect() {
      this.hidePopup()
      this.getMoneyList()
    },
    // 品牌


    handleBuy(item) {
      console.log("点击购买:", item);
      // 处理购买逻辑
      uni.navigateTo({
        url: "/pages/mer/goods/details/details?id=" + item.id,
      });
    },
    async getMoneyList() {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });
      try {
        const res = await this.$request(
          "SmallProgramApi/NewYear/getPriceGoodsList",
          {
            label_id: this.label_id,
            store_id: this.$store.mallStoreId,
            merchant_id: 1,
            sort: this.sort,
            price_start: this.minPrice,
            price_end: this.maxPrice,
            brand_ids:this.brand_ids
          }
        );
        if (res.data) {
          this.goodsFourList = res.data.slice(0, 4);
          this.productFourList = res.data.slice(4, 8);
          this.tenList = res.data.slice(8, 18);
          this.tenList2 = res.data.slice(18, 28);
          this.productList6 = res.data.slice(28, 34);
          this.tenList3 = res.data.slice(34, 44);
          this.tenList4 = res.data.slice(44);
          console.log(res.data, "res.datares.datares.data");
        }
      } catch (error) {
        console.log(error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    handlePriceRange(priceRange) {
      let result = {
        minPrice: null,
        maxPrice: null,
      };

      if (priceRange.includes("以上")) {
        result.minPrice = Number(priceRange.replace("元以上", ""));
      } else if (priceRange.includes("以下")) {
        result.maxPrice = Number(priceRange.replace("元以下", ""));
      } else if (priceRange.includes("-")) {
        const priceArr = priceRange.replace("元", "").split("-");
        result.minPrice = Number(priceArr[0]);
        result.maxPrice = Number(priceArr[1]);
      }

      return result;
    },

    handleMoenyAddToCart(product) {
      // 处理添加到购物车的逻辑
      console.log("Adding to cart:", product);
    },
    handleAddToCart(product) {
      // 处理添加到购物车的逻辑
      console.log("Adding to cart:", product);
    },
    async selectPrice(item, index) {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });

      try {
        // 几百元
        this.title = item;
        this.selectedIndex = index;
        const { minPrice, maxPrice } = this.handlePriceRange(item);
        this.minPrice = minPrice;
        this.maxPrice = maxPrice;
        await this.getMoneyList();
        console.log(this.minPrice, "minPrice");
        console.log(this.maxPrice, "maxPrice");
      } catch (error) {
        console.error('价格筛选失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    backHome() {
      uni.navigateBack();
    },
    async sortBySalesOne() {
      if (this.showPopup) {
        this.hidePopup()
        return
      }
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });
    
      try {
        this.activeTab = "1";
        if (!this.isActiveUp && !this.isActiveDown) {
          this.isActiveUp = true;
          this.isActiveDown = false;
          this.sort = "";
        } else if (this.isActiveUp) {
          this.isActiveUp = false;
          this.isActiveDown = true;
          this.sort = 1;
        } else {
          this.isActiveUp = false;
          this.isActiveDown = false;
          this.sort = "";
        }
        await this.getMoneyList();
      } catch (error) {
        console.error('排序失败:', error);
        uni.showToast({
          title: '排序失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async sortByPriceOne() {
      if (this.showPopup) {
        this.hidePopup()
        return
      }
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });
   
      try {
        this.activeTab = "2";
        if (!this.isActiveUp && !this.isActiveDown) {
          this.isActiveUp = true;
          this.isActiveDown = false;
          this.sort = 2;
        } else if (this.isActiveUp) {
          this.isActiveUp = false;
          this.isActiveDown = true;
          this.sort = 3;
        } else {
          this.isActiveUp = false;
          this.isActiveDown = false;
          this.sort = "";
        }
        await this.getMoneyList();
      } catch (error) {
        console.error('排序失败:', error);
        uni.showToast({
          title: '排序失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async handlerBrand() {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });

      try {
        this.activeTab = "3";
        this.isActiveUp = true;
        this.isActiveDown = false;
      } catch (error) {

      } finally {
        uni.hideLoading();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
  // 品牌弹窗
  .fliter-new-popup {
	position: absolute;
	left: 0;
	right: 0;
	top: 100%;
	z-index: 100;
	
	.fliter-new-popup-content {
	  position: relative;
	  background: #fff;
	  border-radius: 0 0 20rpx 20rpx;
	  padding: 30rpx;
    box-shadow: 0 12rpx 12rpx rgba(0,0,0,0.1);
	  pointer-events: auto;
	  animation: slideIn 0.3s ease forwards;
	  
	  &.fliter-new-slide-out {
		animation: slideOut 0.3s ease forwards;
	  }
	  
	  .fliter-new-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 30rpx;
	  }
	  
	  .fliter-new-brand-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 0 20rpx;
    height: 500rpx;
    overflow-y: auto;
		.fliter-new-brand-item {
		  // height: 64rpx;
		  // line-height: 64rpx;
		  text-align: center;
		  font-size: 26rpx;
		  color: #333;
		  border: 1rpx solid #eee;
		  border-radius: 30rpx;
		  white-space: nowrap;
		  overflow: hidden;
		  text-overflow: ellipsis;
		  padding: 16rpx;
		  box-sizing: border-box;
		  margin: 0 20rpx 20rpx 0;
		  flex: 0 1 auto;
		  min-width: 195rpx;
		  
		  &.fliter-new-active {
			color: #ff4b4b;
			border-color: #ff4b4b;
			background: rgba(255,75,75,0.05);
		  }
		}
	  }
	  
	  .fliter-new-btn-group {
		display: flex;
		gap: 20rpx;
		margin-top: 40rpx;
		padding: 0 20rpx;
		
		.fliter-new-btn {
		  flex: 1;
		  height: 80rpx;
		  line-height: 80rpx;
		  text-align: center;
		  font-size: 28rpx;
		  border-radius: 40rpx;
		  
		  &.cancel {
			background: #f5f5f5;
			color: #666;
		  }
		  
		  &.confirm {
			background: #ff4b4b;
			color: #fff;
		  }
		}
	  }
	}
  }
  
  @keyframes slideIn {
	from {
	  transform: translateY(-20rpx);
	  opacity: 0;
	}
	to {
	  transform: translateY(0);
	  opacity: 1;
	}
  }
  
  @keyframes slideOut {
	from {
	  transform: translateY(0);
	  opacity: 1;
	}
	to {
	  transform: translateY(-20rpx);
	  opacity: 0;
	}
  }
  </style>



<style lang="scss" scoped>
.temperature-box {
  background-color: #C39646;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
  color: #FFFFFF;
  /* 白色文字 */
  font-size: 20rpx;
  /* 文字大小 */
  margin-top: 8rpx;
  height: 28rpx;
  text-align: center;
  padding: 5rpx;
  line-height: 28rpx;
}

.search-box {
  height: 102rpx;
  // padding: 12rpx 24rpx;
  // box-sizing: border-box;
  // box-shadow: 0 0 16rpx rgba(0, 0, 0, 0.05);
  z-index: 1;

  .search-content {
    height: 64rpx;
    width: 448rpx;
    padding: 0 0 0 24rpx;
    border: 2rpx solid var(--primary-color);
    border-radius: 34rpx;
    box-sizing: border-box;
    background-color: #ffffff;

    .search-icon {
      font-size: 28rpx;
      color: #999999;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      line-height: 48rpx;
      color: #333333;
      margin: 0 10rpx;
      height: 48rpx;
    }

    .search-btn {
      width: 124rpx;
      height: 100%;
      font-size: 28rpx;
      color: #ffffff;
      text-align: center;
      line-height: 48rpx;
      // background-color: var(--primary-color);
      border-radius: 32rpx;
      margin-right: -1rpx;
    }
  }
}

.list-money-tail {
  padding-bottom: env(safe-area-inset-bottom);
}

.list-money-boy {
  background-color: #fff;
}

.obj-money-list {
  // background-color: red;
}

.obj-money-card {
  padding: 12px;

  .obj-money-content {
    background: #ffffff;
    border-radius: 12px;
    padding: 12px;
    display: flex;
    align-items: center;
    border: 1px solid #e0b879;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0; // 最后一个元素不需要底部边距
    }

    .obj-money-image {
      width: 264rpx;
      height: 264rpx;
      border-radius: 4px;
      flex-shrink: 0;
    }

    .obj-money-right {
      flex: 1;
      margin-left: 28px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      min-height: 138px;

      .obj-money-title {
        font-size: 15px;
        color: #333;
        line-height: 1.4;
        margin-bottom: 8px;
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        word-break: break-all;
      }

      .obj-money-bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .obj-money-price {
          color: #db5656;

          .obj-money-symbol {
            font-size: 11px;
            margin-right: 2px;
          }

          .obj-money-value {
            font-size: 28rpx;
            font-weight: bold;
          }
        }

        // .obj-money-button {
        //   background-color: #db5656;
        //   color: #fff;
        //   border: none;
        //   border-radius: 20px;
        //   padding: 6px 20px;
        //   font-size: 14px;
        //   margin: 0;

        //   &:active {
        //     opacity: 0.9;
        //   }
        // }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.obj-money-price-range {
  width: 100%;

  .obj-money-scroll-container {
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;

    .obj-money-price-list {
      padding: 10px;
      display: flex;

      .obj-money-price-item {
        padding: 8px 15px;
        margin-right: 10px;
        font-size: 14px;
        color: #333;
        position: relative;

        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 0;
          height: 3px;
          background: #000;
          border-radius: 1px;
          transition: all 0.3s ease;
          opacity: 0;
        }

        &.active::after {
          width: 20px;
          opacity: 1;
        }

        &.active {
          color: #000;
          font-weight: bold;
        }
      }
    }
  }
}
</style>

<style scoped lang="scss">
.benner_box {
  background-color: #fff;
  position: relative;
  width: 100%;
  margin-top: calc(102rpx + 44px);
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
  height: calc(102rpx + 44px);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-color: #ffffff;
}

@media screen and (device-width: 375px) and (device-height: 667px),
/* iPhone 6/7/8 */
screen and (device-width: 414px) and (device-height: 736px),
/* iPhone 6/7/8 Plus */
screen and (device-width: 360px) and (device-height: 640px)
/* 常见安卓机型 */
  {
  .benner_box {
    margin-top: 102rpx;
    background-color: #fff;
  }

  .fixed-header {
    height: 102rpx;
    padding-top: 0;
  }
}
</style>

<style lang="less" scoped>
.options {
  display: flex;
  justify-content: center;
  gap: 100rpx;
  width: 100%;
  margin: 10rpx auto;
  border-radius: 10rpx;
}

.option {
  font-size: 28rpx;
  color: #333;
  text-align: center;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 20rpx;
  transition: color 0.3s;
  position: relative;
}

.option.active {
  color: black;
}

.triangle-icons {
  display: flex;
  flex-direction: column;
  margin-left: 3px;
  gap: 2px;
}

.triangle-icon {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
}

.triangle-icon-up {
  border-bottom: 5px solid #d8d8d8;
}

.triangle-icon-down {
  border-top: 5px solid #d8d8d8;
}

.triangle-icon-up.active {
  border-bottom-color: black;
}

.triangle-icon-down.active {
  border-top-color: black;
}
</style>